package com.guigu.alibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.guigu.alibaba.service.PaymentService;
import com.guigu.springcloud.common.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/nacos/feign")
public class OrderByFeignController {
    @Autowired
    private PaymentService paymentService;

    @GetMapping("/getPayment/{id}")
     @SentinelResource(value = "getPayment") // 什么都不配置
    // @SentinelResource(value = "getPayment", fallback = "handleFallback") // 配置异常处理
//    @SentinelResource(value = "getPayment", fallback = "handleFallback", blockHandler = "blockHandler")
    public CommonResult getPort(@PathVariable("id") Long id) {
        if (id == 5) {
            throw new IllegalArgumentException("非法参数异常");
        }
        CommonResult result = paymentService.getById(id);
        if (result.getData() == null) {
            throw new NullPointerException("空指针异常");
        }
        return result;
    }

    // 程序中的异常处理
    public CommonResult handleFallback(@PathVariable("id") Long id,
                                       Throwable throwable) {
        return CommonResult.voData(444, "异常报错： " + throwable.getMessage(), null);
    }

    // 服务中的降级处理: sentinel中的配置违规
    public CommonResult blockHandler(@PathVariable("id") Long id,
                                     BlockException ex) {
        return CommonResult.voData(400, "服务熔断：" + ex.getMessage(), null);
    }
}
